//
//  SelectCityViewController.m
//  OfficeBook
//
//  Created by 朱 琳 on 15/10/7.
//  Copyright (c) 2015年 sunny. All rights reserved.
//

#import "SelectCityViewController.h"
#import "TableViewHelper.h"
#import "UserDefaultDataHelper.h"
#import "ChineseStringHelper.h"
#import <MAMapKit/MAMapKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import "LocationModel.h"

static NSString *CellIdentifier = @"CityCell";

@interface SelectCityViewController ()
<UITableViewDataSource, UITableViewDelegate, MAMapViewDelegate,AMapSearchDelegate>

// UI property
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *currentCityView;
@property (nonatomic, strong) UILabel *currentCityLabel;
@property (nonatomic, strong) UILabel *tip;
@property (nonatomic, strong) UIActivityIndicatorView *indicatorView;

// Var property
@property (nonatomic, strong) NSMutableArray *cityList;
@property (nonatomic, strong) NSMutableArray *cityNameList;
@property (nonatomic, strong) NSMutableArray *tableIndexList;

// amap
@property (nonatomic, strong) MAMapView *mapView;
@property (nonatomic, strong) AMapSearchAPI *search;

@end

@implementation SelectCityViewController

- (instancetype)init{
    self = [super init];
    if (self) {
        self.cityList = [UserDefaultDataHelper getDataWithKey:UserDefaultKeyCityList];
        self.cityNameList = [[NSMutableArray alloc] init];
        [self.cityList enumerateObjectsUsingBlock:^(id city, NSUInteger idx, BOOL * _Nonnull stop) {
            [self.cityNameList addObject:city[@"name"]];
        }];
        self.tableIndexList = [[NSMutableArray alloc] init];
        self.tableIndexList  = [ChineseStringHelper IndexArray:self.cityNameList];      //根据中文获取索引(段名)
        self.cityNameList = [ChineseStringHelper LetterSortArray:self.cityNameList];        //中文首字母排序并分段
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithHexString:@"#ebebeb"];
    
    [self initNavBarItem];
    [self initCurrentCityView];
    [self initTableView];
    
    // 初始化高德地图定位-key已经在appdelegate中添加
    [self initAmap];
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.mapView.delegate = nil;
    self.search.delegate = nil;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)initAmap {
    self.mapView = [[MAMapView alloc] initWithFrame:CGRectZero];
    self.mapView.delegate = self;
    self.mapView.showsUserLocation = YES;
    self.mapView.distanceFilter = kCLLocationAccuracyHundredMeters;
    self.mapView.desiredAccuracy = kCLLocationAccuracyThreeKilometers;
    
    self.search = [[AMapSearchAPI alloc] init];
    self.search.delegate = self;
    [AMapSearchServices sharedServices].apiKey = AMAP_APIKEY;
}

-(void)initNavBarItem {
    self.navigationItem.title = @"Select City";
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonItemStylePlain target:self action:@selector(cancel:)];
    [self.navigationItem.leftBarButtonItem setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor whiteColor]} forState:UIControlStateNormal];
}

// cancel
-(void)cancel:(UIButton *)sender {
    [self.navigationController popToRootViewControllerAnimated:YES];
}

-(void)initCurrentCityView{
    self.currentCityView = [[UIView alloc]init];
    self.currentCityLabel = [[UILabel alloc] init];
    self.indicatorView = [[UIActivityIndicatorView alloc]init];
    self.tip = [[UILabel alloc]init];
    
    [self.view addSubview:self.currentCityView];
    [self.currentCityView addSubview:self.indicatorView];
    [self.currentCityView addSubview:self.tip];
    [self.currentCityView addSubview:self.currentCityLabel];
    
    [self.currentCityView makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.left);
        make.top.equalTo(self.view.bottom);
        make.right.equalTo(self.view.right);
        make.height.equalTo(@44);
    }];
    self.currentCityView.backgroundColor = [UIColor whiteColor];
    
    [self.currentCityLabel makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.currentCityView.left).offset(10);
        make.centerY.equalTo(self.currentCityView.centerY);
        //make.width.equalTo(@100);
        make.height.equalTo(self.currentCityView);
    }];
    self.currentCityLabel.text = @"Locating...";
    
    [self.indicatorView makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.currentCityLabel.right).offset(10);
        make.centerY.equalTo(self.currentCityView.centerY);
        make.width.equalTo(@44);
        make.height.equalTo(@44);
    }];
    self.indicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
    [self.indicatorView startAnimating];
    
    
    [self.tip makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.currentCityView).offset(-10);
        make.centerY.equalTo(self.currentCityView.centerY);
        make.left.greaterThanOrEqualTo(self.currentCityLabel.right);
        make.height.equalTo(@44);
    }];
    self.tip.text = @"Location City";
    self.tip.textColor = [UIColor colorWithHexString:@"6d6d6d"];
    self.tip.font = [UIFont systemFontOfSize:13];
    self.tip.hidden = YES;
}

-(void)initTableView{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.tableView.translatesAutoresizingMaskIntoConstraints = NO;
    self.tableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.tableView];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:CellIdentifier];
    
    [self.tableView makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
}

#pragma mark AMap delegate
// 地图定位
-(void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation
                                        updatingLocation:(BOOL)updatingLocation
{
    if(updatingLocation)
    {
        self.mapView.showsUserLocation = NO;
        //取出当前位置的坐标
        NSLog(@"latitude : %f,longitude: %f",userLocation.coordinate.latitude,userLocation.coordinate.longitude);
        AMapReGeocodeSearchRequest *regeoRequest = [[AMapReGeocodeSearchRequest alloc] init];
        //regeoRequest.searchType = AMapSearchType_ReGeocode;  3.0没有这个选项
        regeoRequest.location = [AMapGeoPoint locationWithLatitude:userLocation.coordinate.latitude
                                                        longitude:userLocation.coordinate.longitude];
        regeoRequest.radius = 10000;
        regeoRequest.requireExtension = YES;
        
        //发起逆地理编码
        [self.search AMapReGoecodeSearch: regeoRequest];
    }
}

//实现逆地理编码的回调函数
- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response
{
    if(response.regeocode != nil)
    {
        if ([response.regeocode.addressComponent.city isEqual:@""] || response.regeocode.addressComponent.city == nil) {
            // 设置cuurent city label
            self.currentCityLabel.text = [NSString stringWithFormat:@"%@",response.regeocode.addressComponent.province];
        }
        else{
            self.currentCityLabel.text = [NSString stringWithFormat:@"%@",response.regeocode.addressComponent.city];
        }
        
        NSLog(@"ReGeo: %@", self.currentCityLabel.text);
        self.indicatorView.hidden = YES;
        self.tip.hidden = NO;
        // 定位结束添加手势
        UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectCurrentCity)];
        [self.currentCityView addGestureRecognizer:gestureRecognizer];
    }
}

-(void)selectCurrentCity{
    NSString *locationCity = self.currentCityLabel.text;     //定位城市
#warning fixme
    [self.cityList enumerateObjectsUsingBlock:^(NSDictionary *locationInfo, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([locationInfo[@"name"] isEqualToString:locationCity]) {
            LocationModel *location = [[LocationModel alloc] init];
            location.id = [locationInfo[@"id"] intValue];
            location.name = locationInfo[@"name"];
            [self.delegate viewController:self didSelectLocation:location];
            *stop = YES;
        }
    }];
}

#pragma mark - Table view data source

//获取分区数 26个英文字母
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [self.tableIndexList count];
}

//分区头名字
-(NSString*) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return  self.tableIndexList[section];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.cityNameList[section] count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30.0f;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 45.0f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    cell.textLabel.text = [self.cityNameList[indexPath.section] objectAtIndex:indexPath.row];
    return cell;
}

//选中某行
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //获取选中行
    NSString* cityName = [self.cityNameList[indexPath.section] objectAtIndex:indexPath.row];
    [self.cityList enumerateObjectsUsingBlock:^(NSDictionary *locationInfo, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([locationInfo[@"name"] isEqualToString:cityName]) {
            LocationModel *location = [[LocationModel alloc] init];
            location.id = [locationInfo[@"id"] intValue];
            location.name = locationInfo[@"name"];
            [self.delegate viewController:self didSelectLocation:location];
            [self.navigationController popViewControllerAnimated:YES];
            *stop = YES;
        }
    }];
}

@end
